var _util = require('../../util/util.js');
require('../Order/index.css');
require('./myOrder.js');  // 绑定事件逻辑
require('./autoUpdate.js');


console.log('看一下当前用户：' + localStorage.getItem('userInfo'))
var user = JSON.parse(localStorage.getItem('userInfo')) 
var userId = user.id;
console.log(userId);

const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '待取件',
    4: '已签收',
    5: '商家已处理售后',
    10: '已取消订单',
    11: '已申请售后'
};

const renderButtons = (status, orderId) => {
    const btn = (className, text) => `<button class="${className}" data-id="${orderId}">${text}</button>`;
    switch (status) {
        case 0:
            return btn('cancel', '取消订单') + btn('pay', '支付') + btn('check_info', '查看订单信息');
        case 1:
            return btn('after_sale', '申请售后') + btn('check_info', '查看订单信息');
        case 2:
        case 3:
            return btn('after_sale', '申请售后') + btn('confirm', '确认收货') + btn('check_info', '查看订单信息');
        case 4:
            return btn('after_sale', '申请售后') + btn('check_info', '查看订单信息');
        case 5:
            return btn('after_sale', '申请售后') + btn('check_solve', '查看处理结果') + btn('check_info', '查看订单信息');
        case 11:
            return btn('after_sale', '申请售后') + btn('confirm', '确认收货') + btn('check_info', '查看订单信息');
        default:
            return '';
    }
};

function renderOrders(orderItems) {
    const tbody = document.getElementById('orderTableBody');
    tbody.innerHTML = '';

    orderItems.forEach(item => {
        const subtotal = item.price * item.itemNum;
        const tr = document.createElement('tr');
        console.log("状态值：", item.status, typeof item.status);
        tr.innerHTML = `
      <td>
        <img src="${item.url}" style="width:100px;height:auto;" alt="商品图片"><br>
        <span>${item.name}</span>
      </td>
      <td>¥${item.price}</td>
      <td>${item.itemNum}</td>
      <td>¥${subtotal.toFixed(2)}</td>
      <td><span class="status">${statusMap[item.status] || '未知状态'}</span></td>
      <td>
        <div class="order-status" data-id="${item.order_id}">
          ${renderButtons(item.status, item.order_id)}
        </div>
      </td>
    `;
        tbody.appendChild(tr);
    });
}

async function getOrderItems() {
    try {
        const res = await fetch(`http://localhost:8080/order/orders/${userId}`, {
            method: 'GET',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' }
        });
        if (!res.ok) throw new Error(res.status);
        const result = await res.json();
        renderOrders(result.data);
    } catch (error) {
        console.error('获取订单失败：', error);
    }
}

getOrderItems();